<template>
  <div>
    <!-- 弹出框 -->
    <el-dialog
      title="收货地址"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div class="edit-address">
        <div class="item">
          <input
            type="text"
            placeholder="请输入收货人姓名"
            v-model="informations.name"
            @blur="checkName"
          />
          <div class="tips error" v-show="nameCheck">请输入姓名</div>
        </div>
        <div class="item">
          <div class="flex">
            <el-select v-model="selectProvince" placeholder="请选择省">
              <el-option
                v-for="item in provinces"
                :key="item.key"
                :label="item.label"
                :value="item.cityname"
              >
              </el-option>
            </el-select>
            <el-select v-model="selectcity" placeholder="请选择市">
              <el-option
                v-for="item in citys"
                :key="item.key"
                :label="item.label"
                :value="item.cityname"
              >
              </el-option>
            </el-select>
            <el-select v-model="selectdistrict" placeholder="请选择区">
              <el-option
                v-for="item in districts"
                :key="item.key"
                :label="item.label"
                :value="item.cityname"
              >
              </el-option>
            </el-select>
          </div>
          <div class="tips error" v-show="cityCheck">请选择城市</div>
        </div>
        <div class="item">
          <input
            type="text"
            placeholder="请输入收货地址"
            v-model="informations.desc"
            @blur="checkDesc"
          />
          <div class="tips error" v-show="descCheck">请输入地址</div>
        </div>
        <div class="item">
          <input
            type="text"
            placeholder="请输入手机号码"
            v-model="informations.phone"
            @blur="checkPhone"
          />
          <div class="tips error" v-show="phoneCheck">请输入手机号</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addMyAddress">确 定</el-button>
      </span>
    </el-dialog>
    <div class="line"></div>
    <div class="container">
      <div class="cart-title">
        <h1>填写并核对订单信息</h1>
      </div>
      <div class="address">
        <h4>收货人信息</h4>
        <div class="cls">
          <ul
            class="address-show"
            v-nav-active="{
              className: 'select',
              classActive: 'current',
              currentIndex,
            }"
            v-if="addressList.length"
          >
            <li
              class="select"
              v-for="(item, index) in addressList"
              :key="index"
              @click="handleChange(index)"
            >
              <div class="send-title">
                <span>{{ item.name }}</span>
                <span>
                  <a
                    href="javascript:void(0);"
                    class="address_edit"
                    @click.stop="editAddress(item)"
                    >[编辑]</a
                  >
                  {{ item.phone }}
                </span>
              </div>
              <div class="region">{{ item.area_name.split("-")[0] }}</div>
              <div class="user-address">{{ item.desc }}</div>
            </li>
          </ul>
          <div class="address-add" @click="dialogVisible = true">
            <span class="add">+</span>
            <span>新增收货人</span>
          </div>
        </div>
      </div>
      <div class="sub-cart">
        <table>
          <thead>
            <tr>
              <th>商品名称</th>
              <th>单价</th>
              <th>数量</th>
              <th>小计</th>
            </tr>
          </thead>
          <tbody v-if="!checkout">
            <tr class="line"></tr>
            <tr v-for="(item, index) in orderProducts" :key="index">
              <td>{{ item.s_good.desc.split("-")[0] }}</td>
              <td>{{ item.s_good.sale_price }}</td>
              <td>{{ item.num }}</td>
              <td>{{ item.s_good.sale_price * item.num }}</td>
            </tr>
          </tbody>
          <tbody v-if="checkout">
            <tr class="line"></tr>
            <tr>
              <td>{{ checkout.desc.split("-")[0] }}</td>
              <td>{{ checkout.sale_price }}</td>
              <td>1</td>
              <td>{{ checkout.sale_price }}</td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td></td>
              <td></td>
              <td>商品总额:</td>
              <td>￥{{ totalPrice }}</td>
            </tr>
          </tfoot>
        </table>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item title="优惠券（无优惠券）" name="1">
          <div>
            <input type="radio" />
            <div>不使用优惠券</div>
          </div>
          <div>
            <div>使用优惠券兑换码</div>
            <input type="text" />
            <button>确定</button>
          </div>
        </el-collapse-item>
        <el-collapse-item title="代金券（无代金券）" name="2">
          <input type="radio" checked />
          <div>不使用代金券</div>
        </el-collapse-item>
        <el-collapse-item
          :title="`发票（普通发票，商品明细，${buyer}）`"
          name="3"
        >
          <div>
            <label>
              <input
                type="radio"
                name="debit note"
                value="1"
                v-model="invoice"
              />
              <div>不需要发票</div>
            </label>
          </div>
          <div>
            <label>
              <input
                type="radio"
                name="debit note"
                value="2"
                v-model="invoice"
              />
              <div>普通发票</div>
            </label>
          </div>
          <table v-show="invoice == 2">
            <tbody>
              <tr>
                <td><span class="red">*</span>发票类型</td>
                <td><span class="redBorder">电子发票</span></td>
              </tr>
              <tr>
                <td><span class="red">*</span>发票内容</td>
                <td><span class="redBorder">商品明细</span></td>
              </tr>
              <tr>
                <td><span class="red">*</span>发票抬头</td>
                <td class="middle-center">
                  <div>
                    <label
                      ><input
                        type="radio"
                        name="invoice_title"
                        value="1"
                        v-model="checkValue"
                      />个人</label
                    >
                    <label
                      ><input
                        type="radio"
                        name="invoice_title"
                        value="2"
                        v-model="checkValue"
                      />企业</label
                    >
                  </div>
                  <div class="red">
                    自17年7月1日起，财税{2017}16号要求：增值税普通发票购买方为企业名称的用户，"购方纳税人识别号"必填。
                  </div>
                </td>
              </tr>
              <tr v-show="checkValue == 1">
                <td><span class="red">*</span>客户名称</td>
                <td><input type="text" value="客户" /></td>
              </tr>
              <tr v-show="checkValue == 2">
                <td><span class="red">*</span>公司名称</td>
                <td><input type="text" value="" /></td>
              </tr>
              <tr v-show="checkValue == 2">
                <td><span class="red">*</span>纳税人识别码</td>
                <td><input type="text" value="" /></td>
              </tr>
            </tbody>
          </table>
        </el-collapse-item>
        <el-collapse-item title="配送方式" name="4">
          <input type="radio" checked />
          <div>免运费</div>
        </el-collapse-item>
      </el-collapse>
      <div class="cart-end">
        优惠后商品总额:
        <span class="red">￥{{ totalPrice }}</span>
      </div>
      <div class="cart-end">
        合计抵扣:
        <span class="red">￥0</span>
      </div>
      <div>
        <div class="left">
          <h4>订单附言:</h4>
          <textarea
            name="order_message"
            id=""
            cols="60"
            placeholder="输入200个以内文字!"
            rows="5"
          ></textarea>
        </div>
        <div class="right">
          <div class="order-price">
            订单金额:
            <span class="red">￥{{ totalPrice }}</span>
            <p>(免运费)</p>
          </div>
          <div class="sub-btn">
            <button @click="$router.push('/cart')">返回购物车</button>
            <button @click="toOrder">立即下单</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCart, addCart, delCart } from "../assets/js/request.js";
import { mapState, mapActions } from "vuex";
import NavActive from "../directives/navActive.js";
import {
  getCity,
  addAddress,
  getAddress,
  delAddress,
  updateAddress,
  order,
} from "../assets/js/request.js";
export default {
  data() {
    return {
      //立即下单列表
      checkout: JSON.parse(sessionStorage.getItem("checkout")) || "",
      //切换地址选项
      currentIndex: 0,
      //地址信息
      addressList: [],
      activeNames: ["3", "4"],
      dialogVisible: false,
      //省份数组
      provinces: [],
      //城市数组
      citys: [],
      //区数组
      districts: [],
      //选择的地址的id集合
      selectIds: [],
      //选择的省份
      selectProvince: "",
      //选择的城市
      selectcity: "",
      //选择的区
      selectdistrict: "",
      //地址信息
      informations: {
        name: "",
        phone: "",
        area: ``,
        area_name: "",
        desc: "",
      },
      //发票开方
      checkValue: 1,
      //是否需要发票
      invoice: 2,
      //判断是修改地址还是新增地址
      edit: false,
      editId: "",
      //判断是购物车来的还是立即购买
      flag: "",
      nameCheck: false,
      cityCheck: false,
      descCheck: false,
      phoneCheck: false,
    };
  },
  computed: {
    ...mapState("cart", ["cartProducts"]),
    totalPrice() {
      if (this.checkout) {
        return this.checkout.sale_price;
      } else {
        let sum = 0;
        this.cartProducts.forEach((ele) => {
          if (ele.isChecked == true) {
            sum += ele.s_good.sale_price * ele.num;
          }
        });
        return sum;
      }
    },
    buyer() {
      if (this.checkValue == 1) {
        return "客户";
      } else {
        return "企业";
      }
    },
    orderProducts() {
      return this.cartProducts.filter((ele) => ele.isChecked == true);
    },
  },
  watch: {
    selectProvince(newval, oldval) {
      if (newval) {
        this.citys = this.provinces.filter((ele) => {
          this.selectIds[0] = ele.id;
          return ele.cityname == newval;
        })[0].children;
      }
    },
    selectcity(newval, oldval) {
      if (newval) {
        this.districts = this.citys.filter((ele) => {
          this.selectIds[1] = ele.id;
          return ele.cityname == newval;
        })[0].children;
      }
    },
    selectdistrict(newval, oldval) {
      if (newval) {
        this.districts.forEach((ele) => {
          if (ele.cityname == newval) {
            this.selectIds[2] = ele.id;
          }
        });
      }
    },
  },
  directives: {
    NavActive,
  },
  methods: {
    ...mapActions("cart", ["clearCartOut", "addtocart", "delone", "buynow"]),
    checkName() {
      if (this.informations.name == "") {
        this.nameCheck = true;
      } else {
        this.nameCheck = false;
      }
    },
    checkCity() {
      if (
        this.selectProvince == "" ||
        this.selectcity == "" ||
        this.selectdistrict == ""
      ) {
        this.cityCheck = true;
      } else {
        this.cityCheck = false;
      }
    },
    checkDesc() {
      if (this.informations.desc == "") {
        this.descCheck = true;
      } else {
        this.descCheck = false;
      }
    },
    checkPhone() {
      if (this.informations.phone == "") {
        this.phoneCheck = true;
      } else {
        this.phoneCheck = false;
      }
    },
    //切换地址
    handleChange(index) {
      this.currentIndex = index;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.edit = false;
          this.clearEdit();
        })
        .catch((_) => {});
    },
    addMyAddress() {
      let flag = true;
      for (let key in this.informations) {
        flag = this.informations[key] == "" ? !flag : flag;
      }
      if (flag) {
        this.informations.area = this.selectIds.join(",");
        this.informations.area_name =
          this.selectProvince +
          this.selectcity +
          this.selectdistrict +
          `-${this.selectProvince},${this.selectcity},${this.selectdistrict}`;
        if (this.edit) {
          let data = {};
          data.name = this.informations.name;
          data.phone = this.informations.phone;
          data.area = this.informations.area;
          data.desc = this.informations.desc;
          data.area_name =
            this.selectProvince +
            this.selectcity +
            this.selectdistrict +
            `-${this.selectProvince},${this.selectcity},${this.selectdistrict}`;
          updateAddress(this.editId, data).then(() => {
            this.dialogVisible = false;
            this.edit = false;
            getAddress().then((res) => {
              this.addressList = res;
            });
            this.clearEdit();
          });
        } else {
          addAddress(this.informations).then(() => {
            this.dialogVisible = false;
            getAddress().then((res) => {
              this.addressList = res;
            });
            this.clearEdit();
          });
        }
      }
    },
    //修改地址信息
    editAddress(item) {
      this.edit = true;
      this.editId = item.id;
      this.informations.name = item.name;
      this.informations.phone = item.phone;
      this.informations.desc = item.desc;
      this.selectProvince = item.area_name.split("-")[1].split(",")[0];
      this.selectcity = item.area_name.split("-")[1].split(",")[1];
      this.selectdistrict = item.area_name.split("-")[1].split(",")[2];
      this.dialogVisible = true;
    },
    //删除地址
    del(id) {
      delAddress(id);
    },
    //清空地址输入框
    clearEdit() {
      for (let key in this.informations) {
        this.informations[key] = "";
      }
      this.selectProvince = "";
      this.selectcity = "";
      this.selectdistrict = "";
    },

    //下单
    toOrder() {
      if (this.addressList.length) {
        let data = {
          addr_id: this.addressList[this.currentIndex].id,
          project_id: 13,
          goods_info: [],
        };
        //立即购买跳转过来的
        if (this.checkout) {
          data.goods_info.push({
            id: this.checkout.id,
            num: 1,
          });
          order(data).then((res) => {
            this.$router.push(`/pay/${res.id}`);
          });
          //购物车过来的
        } else {
          this.orderProducts.forEach((ele) => {
            data.goods_info.push({
              id: ele.s_good.id,
              num: ele.num,
            });
          });
          order(data).then((res) => {
            this.$router.push(`/pay/${res.id}`);
            this.clearCartOut();
          });
        }
        sessionStorage.removeItem("checkout");
      } else {
        this.$message.error("地址不能为空");
      }
    },
  },
  created() {
    this.flag = this.$route.params.flag || "";
    getCity().then((res) => {
      this.provinces = res;
    });
    getAddress().then((res) => {
      this.addressList = res;
    });
  },
  beforeDestroy() {
    sessionStorage.removeItem("checkout");
  },
};
</script>

<style lang='scss'>
.el-dialog__wrapper {
  input {
    display: block;
    width: 100%;
    height: 40px;
    padding-left: 8px;
  }
  .edit-address {
    padding: 0 30px;
    .item {
      position: relative;
      margin-bottom: 25px;
      .flex {
        display: flex;
        justify-content: space-between;
      }
      .tips {
        position: absolute;
        left: 0;
        bottom: -25px;
        width: 100%;
        height: 25px;
        color: #ee0a3b;
      }
      .tips.error::before {
        display: inline-block;
        vertical-align: middle;
        content: "";
        width: 18px;
        height: 20px;
        background: url(../assets/image/register/icons-201703.png) -66px 0 no-repeat;
      }
    }
    .el-select {
      width: 120px;
    }
  }
  .el-dialog__footer {
    text-align: center;
    .el-button {
      background-color: #ee0a3b;
      border: 1px solid #ee0a3b;
      color: #fff;
    }
  }
}
.line {
  border: 1px solid rgb(241, 233, 233);
}
.line + .container {
  width: 1100px;
  margin-bottom: 35px;
  .cart-title {
    padding-top: 20px;
    h1 {
      font: 400 24px/1.5 Microsoft YaHei, STHeiti, sans-serif;
      color: #172b40;
    }
  }
  .address {
    margin: 10px auto 0;
    border: 1px solid #dfdfdf;
    padding: 15px;
    background-color: #f8f8f8;
    overflow: hidden;
    h4 {
      margin-bottom: 5px;
      font-weight: 400;
    }
    .address-show {
      display: block;
      float: left;
      max-width: 946px;
      .select {
        margin-right: 15px;
        display: block;
        float: left;
        width: 300px;
        padding: 10px;
        margin-bottom: 10px;
        height: 110px;
        background-color: #fff;
        .send-title {
          border-bottom: 1px solid #ddd;
          height: 25px;
          line-height: 25px;
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          a {
            color: #666;
            &:hover {
              color: #ee0a3b;
            }
          }
        }
        & > div {
          font-size: 14px;
        }
      }
      .select.current {
        border: 1px solid #ee0a3b;
        background: url(../assets/image/cart/OK201608.png) right bottom
          no-repeat #fff;
      }
    }
    .address-add {
      display: block;
      float: left;
      width: 102px;
      height: 110px;
      padding: 10px;
      text-align: center;
      border: 1px solid #ddd;
      background-color: #fff;
      cursor: pointer;
      .add {
        width: 82px;
        height: 57px;
        line-height: 57px;
        display: block;
        font-size: 38px;
        color: #999;
        text-align: center;
      }
      .add + span {
        font-size: 14px;
        &:hover {
          color: #ee0a3b;
        }
      }
    }
  }
  .sub-cart {
    width: 100%;
    margin: 10px auto 0;
    border: 1px solid #dfdfdf;
    padding: 15px;
    background-color: #f8f8f8;
    table {
      width: 100%;
      border-collapse: collapse;
      border-spacing: 0;
      thead {
        height: 30px;
        line-height: 30px;
        border-bottom: 1px solid #eee;
        tr {
          background-color: rgb(238, 238, 238);
          th {
            padding: 3px 10px;
            text-align: center;
            font-size: 14px;
            font-weight: 400;
          }
        }
      }
      tbody {
        tr {
          height: 30px;
          line-height: 30px;
          border-bottom: 1px solid #eee;
          text-align: center;
          td {
            padding: 3px 10px;
            font-size: 14px;
            font-weight: 400;
            &:first-of-type {
              text-align: left;
            }
          }
        }
        .line {
          border-bottom: 1px solid #ccc;
          height: 8px;
        }
      }
      tfoot {
        height: 30px;
        line-height: 30px;
        border-bottom: 1px solid #eee;
        tr {
          background-color: rgb(238, 238, 238);
          td {
            padding: 3px 10px;
            text-align: center;
            font-size: 14px;
            font-weight: 400;
            &:last-of-type {
              font-size: 20px;
              color: #ee0a3b;
            }
          }
        }
      }
    }
  }
  .el-icon-arrow-right {
    &::before {
      content: "";
    }
  }
  .el-collapse {
    margin: 35px auto 0;
    .el-collapse-item {
      .el-collapse-item__header {
        &::before {
          display: inline-block;
          content: "+";
          background-color: #999;
          color: #fff;
          height: 18px;
          line-height: 18px;
          width: 18px;
          margin-right: 5px;
          text-align: center;
          font-style: normal;
        }
      }
      .el-collapse-item__header.is-active {
        &::before {
          content: "-";
        }
      }
      .el-collapse-item__content {
        padding: 15px 0 34px 25px;
        input[type="radio"] {
          display: inline-block;
          margin-right: 5px;
        }
        input[type="radio"] + div {
          display: inline-block;
        }
        & > div {
          div {
            display: inline-block;
          }
          input[type="text"] {
            margin: 0;
            vertical-align: middle;
            height: 30px;
            line-height: 30px;
            box-sizing: border-box;
            margin: 0 5px;
          }
          button {
            padding: 0 5px;
            height: 30px;
            line-height: 30px;
            vertical-align: -2px;
            display: inline-block;
            background-color: #ee0a3b;
            font-size: 14px;
            text-align: center;
            border: 1px solid #ee0a3b;
            outline: 0;
            color: #fff;
            cursor: pointer;
          }
        }
        table {
          border-collapse: collapse;
          border-spacing: 0;
          .red {
            color: #ee0a3b;
          }
          tr {
            font-size: 12px;
            td:first-of-type {
              font-size: 14px;
              color: #333;
              height: 55px;
              padding-left: 20px;
              width: 180px;
            }
            td {
              .redBorder {
                display: inline-block;
                color: #666;
                font-size: 12px;
                border: 1px solid #ee0a3b;
                width: 92px;
                height: 31px;
                line-height: 23px;
                padding: 3px 15px;
                margin-right: 20px;
                text-align: center;
                background: url(../assets/image/cart/sanjiao.png) right bottom
                  no-repeat;
              }
              input[type="text"] {
                width: 314px;
                height: 31px;
                padding: 3px 5px;
                font-size: 14px;
              }
            }
            .middle-center {
              label {
                input {
                  vertical-align: middle;
                }
              }
              .red {
                font-size: 14px;
              }
            }
          }
        }
      }
    }
  }
  .cart-end {
    padding-top: 30px;
    margin: 10px auto 10px;
    text-align: right;
    font-size: 14px;
    .red {
      color: #ee0a3b;
    }
    &:last-of-type {
      border-top: 1px solid #ddd;
      margin: 0 auto 35px;
    }
  }
  .left {
    display: inline-block;
    width: 50%;
    h4 {
      margin-bottom: 10px;
      font-size: 14px;
      font-weight: 400;
    }
  }
  .right {
    display: inline-block;
    width: 50%;
    text-align: right;
    .sub-btn {
      button {
        font-size: 16px;
        text-align: center;
        width: 140px;
        background-color: #ee0a3b;
        color: #fff;
        height: 34px;
        line-height: 34px;
        margin-top: 20px;
        cursor: pointer;
        border: 0;
        &:first-of-type {
          background-color: #fff;
          color: #333;
          border: 1px solid #ddd;
          margin-top: 20px;
          margin-right: 15px;
        }
      }
    }
  }
}
</style>